// pages/tiku/tiku.js
const App = getApp();
const api = require("../../../utils/api.js");

Page({
    //页面的初始数据
    data: {
        url: '',
        //索引
        swiperIndex: 0,
        //倒计时
        timer: '',
        //定时器名字
        countDownNum: '3600',
        //倒计时初始值
        timer_H: '00',
        //m
        timer_M: '60',
        //m
        timer_S: '00',
        //s
        isSuspend: '0',
        //是否暂停
        Hour: '',
        Minu: '',
        senc: '',
        timerMask: false,
        jsonstr: '',
        options: '',
        jsonlist: [],
        list: "",
        json: [],
        activeIndex: 1,
        chooseValue: [],
        // 选择的答案序列
        answerMask: false,
        sheet: [],
        topic: [],
        //题型
        colllist: [],
        //收藏
        back: [],
        //收藏
        colors: [],
        //中转背景颜色
        color: [],
        //背景颜色
        submitlist: [],
        //提交答卷
        err: [],
        //错题,
        parmas: '',
        kaoqi: '',
        suff: '',
        qid: [],
        startTimes: 0,
        nowTimes: 0,
        endTimes: 0,
        wastetime: 0,
        totalwastetime: 0,
        lastqid: 0,
        rightAnswer: [],
    },
    onReady: function () {
        // this.mybox = this.selectComponent("#mybox")
        // this.collection = this.selectComponent("#collection")
    },

    //生命周期函数--监听页面加载
    onLoad: function (option) {
        this.dosendPost(option); //调用两次请求
        this.countDown()
        this.times();
    },
    //计时器-暂停-继续
    setSuspend(e) {
        let that = this;
        let isSuspend = that.data.isSuspend;
        let countDownNum = that.data.countDownNum;
        if (isSuspend == 0) {
            isSuspend = '1';
        } else {
            isSuspend = '0';
        }
        that.checkTime();
        that.setData({
            isSuspend: isSuspend,
            //是否暂停
            timerMask: !that.data.timerMask,

        })
    },
    countDown: function () {
        let that = this;
        var h, m, s;
        let countDownNum = that.data.countDownNum; //1440
        that.setData({
            timer: setInterval(function () {
                    let isSuspend = that.data.isSuspend;

                    if (isSuspend == 0) {
                        countDownNum--;
                        h = Math.floor(countDownNum / 3600);
                        m = Math.floor(countDownNum / 60);
                        s = Math.floor(countDownNum % 60);
                        if (h < 10) {
                            h = "0" + h;
                        }
                        if (m < 10) {
                            m = "0" + m;
                        }
                        if (s < 10) {
                            s = "0" + s;
                        }
                        that.setData({
                            countDownNum: countDownNum,
                            timer_H: h,
                            timer_M: m,
                            timer_S: s
                        })
                        if (countDownNum == 0) {
                            clearInterval(that.data.timer);
                        }
                    }
                },
                1000)
        })
    },
    dosendPost: function (option) {
      
        const that = this;
        var json = that.data.json;
        var topic = that.data.topic;
        var parmas = JSON.parse(option.parmas);

        that.setData({
            parmas: parmas,
            url: option.url,
        })
        var url = that.data.url;
        var arrs = [];
        var t = 0;
        //得到全部数据
        api.sendPosts(url, parmas, function (res) { //第一次请求
     
            that.data.suff = res.suff;
            that.data.kaoqi = res.kaoqi;
            var length = res.list.length;
            var data = res.timing;
            var title;
            var t = 0;
            that.setData({
                sum: length,
                countDownNum: data,
            })

            var submitParmars = {
                sessionid: parmas.sessionid,
                uid: parmas.uid,
                state: '1',
                accuracy: '',
                paperid: res.paperid,
                lastqid: '',
                type: parmas.type,
                wastetime: ''
            }
            that.data.submitlist = submitParmars;
            var chooseValue = that.data.chooseValue;
            var color = that.data.color;
            var index = that.data.swiperIndex; 
           
           
            for (var i = 0; i < res.list.length; i++) {
                //获取上一次答题信息
                //获取我的答案
                that.data.qid[i] = res.list[i].qid;
                if (url == "/study/loadrecordpaper") {
                    chooseValue[i] = parseInt(res.list[i].useranswer);
                    color[i]=chooseValue[i];
                    index=res.lastqid;
                    that.setData({
                        chooseValue: chooseValue,
                        color:color,       
                    })
                }
                var parmarsss = {
                    sessionid: parmas.sessionid,
                    uid: parmas.uid,
                    courseid: parmas.courseid,
                    unitid: parmas.unitid,
                    qid: res.list[i].qid,
                    paperid: res.paperid,
                    type: parmas.type,
                    market: parmas.market,
                    videosource: "aly"
                }
                var colllistParmars = {
                    sessionid: parmas.sessionid,
                    uid: parmas.uid,
                    courseid: parmas.courseid,
                    unitid: parmas.unitid,
                    qid: res.list[i].qid,
                    type: parmas.type,
                    state: ''
                }
                that.data.colllist[i] = colllistParmars;
                var urls = "/question/loadQuestion";
                api.sendPosts(urls, parmarsss,function (res) { //第二次请求
                        var a;
                        topic.push(res.mainque[0].quetypename) //题型
                        arrs[t] = res.mainque[0].content; //得到没有解析的xml
                        var xml = that.getxmls(arrs[t], t, length,res.mainque[0].quetypename); //得到解析后的数组
                        if(res.mainque[0].zhishidian[0]){
                            xml.push(res.mainque[0].zhishidian[0].knowpoint);
                            xml.push(res.mainque[0].zhishidian[0].videocode);
                        }else{
                            xml.push("");
                            xml.push("");
                        }

                       
                        xml.push(res.mainque[0].quetypename);
                        json.push(xml); //解析xml
                        t++;
                        that.setData({
                            options: json,
                            topic: topic
                        })
                    });

            }
        });



    },
    getxmls: function (a, t, length,type) {

        const that = this;
        var jsonlist = that.data.jsonlist;
        var json = that.data.jsonstr;
        var jsonsss = [];
        jsonsss[t] = a;
        //处理数据
        var X2JS = require('../../../utils/x2j/x2js/we-x2js');
        var x2js = new X2JS();
        json = x2js.xml2js(jsonsss[t]);
        var title = json.Question.Title;
        //有可能成为二维数组
        var OptionList = json.Question.OptionList; //答案
        var Explanation = json.Question.Explanation; //答案解析
        var Extent = json.Question.Extent; //难度
        var str = json.Question.Option;//答案选项
        var arrs = [];
        if(type=="写作题" || type =="材料分析题"){
            arrs.push(title);
            arrs.push(Explanation);
            arrs.push(Extent);
            return arrs;
        }else{

            var arr = str.split('|b#k*w|')
            
            arrs.push(title);
            for (var i = 0; i < arr.length; i++) {
                arrs.push(arr[i])
            }
            arrs.push(OptionList);
            arrs.push(Explanation);
            arrs.push(Extent);
            return arrs;
        }
    },
    //设置当前页面索引
    moveServerProSwiper: function (e) {
        var that = this;
        that.setData({
            swiperIndex: e.detail.current,
        })
     
    },
    //点击跳转下一条
    changeCheck: function (e) {
        const that = this;
        var chooseValue = that.data.chooseValue;
        var value = e.currentTarget.dataset.question
        var colorIndex = e.currentTarget.dataset.index;
        chooseValue[that.data.swiperIndex] = value;
        var index;
        if (that.data.swiperIndex + 1 != that.data.sum) {
            index = that.data.swiperIndex + 1;
        } else {
            index = that.data.swiperIndex;
        }
        var useranswer;
        switch (value) {
            case 'A':
                useranswer = 1;
                break;
            case 'B':
                useranswer = 2;
                break;
            case 'C':
                useranswer = 3;
                break;
            case 'D':
                useranswer = 4;
                break;
        }
        var isright;
        var isrightCount = 0;
        var isErrorCount = 0;
        that.setData({
            chooseValue: chooseValue,
            ["color[" + that.data.swiperIndex + "]"]: colorIndex,
            swiperIndex: index,
        })
        var question = that.data.json[that.data.swiperIndex - 1][5];
        if (useranswer == question) {
            isright = 1;
            isrightCount++;
        } else {
            isright = 2;
            isErrorCount++;
        }
        that.times();
        var parmas = {
            sessionid: that.data.parmas.sessionid,
            uid: that.data.parmas.uid,
            paperid: that.data.submitlist.paperid,
            courseid: that.data.parmas.courseid,
            qid: that.data.qid[that.data.swiperIndex-1],
            wastetime: that.data.wastetime,
            useranswer: useranswer, //用户答案 数组
            isright: isright,
            rightnum: isrightCount,
            wrongnum: isrightCount,
            totalwastetime: that.data.totalwastetime,
            kaoqi: that.data.kaoqi,
            type: that.data.parmas.type,
            suffll: that.data.suff,
            letter: value, //用户答案字母
            unitid: that.data.parmas.unitid, //章id
            lastqid: that.data.swiperIndex,
            suff: that.data.suff,
        }

        var url = "/study/saveanswerinfo";
        api.sendPosts(url, parmas, function (res) {
            console.log("保存答题进度成功。")
        })
        
    },
    //答题卡
    submitBtnHandle: function (e) {
        const that = this;
        var sheets = [];
        var chooseValue = that.data.chooseValue;

        for (var i = 0; i < this.data.sum; i++) {
            sheets.push(i + 1)
        }
        this.setData({
            answerMask: !this.data.answerMask,
            sheet: sheets,
        })
    },
    //答题卡跳转
    goIndexQuestion: function (e) {
        const that = this;
        var index = e.currentTarget.dataset.indexs - 1;
        that.setData({
            swiperIndex: index,
            answerMask: !that.data.answerMask,
        })
        
    },
    //自定义组件
    showBox: function () {
        console.log("开始执行showBox方法")
        const that = this;
        var value = that.data.chooseValue;
        var t = 0;
        for(var i = 0;i<value.length;i++){
            if(value[i]) 
                 t++;
        }
        if(value.length!=t){
            wx.showModal({
                title: '确认提交',
                content: '检测到你有未答的题目，确定提交？',
                confirmColor:'#FECC34',
                success (res) {
                  if (res.confirm) {
                    that._success();
                  } else if (res.cancel) {
                    that._error();
                  }
                }
            });
        }else{
            that._success();
        }
       
        that.setData({
            isSuspend: 1,
        })
    },
    showCollection: function () {
        const that = this;
        var back = that.data.back;
        var parmas = that.data.colllist;

        if (parmas[that.data.swiperIndex].state == 0) {
            parmas[that.data.swiperIndex].state = 1;
            back[that.data.swiperIndex] = "https://imgcdn.cnbkw.com/wechat_yitiku_applet_img/doExam/shouchang-yellow-icon.png";
        } else {
            back[that.data.swiperIndex] = "https://imgcdn.cnbkw.com/wechat_yitiku_applet_img/doExam/shouchang-icon.png";
            parmas[that.data.swiperIndex].state = 0;
        }
        that.setData({
            colllist: parmas,
            back: back,
        })
        this.collection.showCollection(parmas[that.data.swiperIndex].state);
        var url = "/study/collectQuestion"

        api.sendPosts(url, parmas[that.data.swiperIndex],
            function (res) {})

    },
    _error: function () {
        console.log("执行了去取消操作")
        this.setData({
            isSuspend: 0,
        })
    },
    _success: function () {
        const that = this;
        console.log("执行了去确定操作")
        var arr = [];
        var arrs = ['A', 'B', 'C', 'D'];
        var params = that.data.submitlist;

        //当前的索引
        var index = that.data.swiperIndex + 1;
        //我的答题序列
        var chooseValue = that.data.chooseValue;
        for (var i = 0; i < chooseValue.length; i++) {
            if (chooseValue[i] == 'A') {
                chooseValue[i] = 1;
            }

            if (chooseValue[i] == 'B') {
                chooseValue[i] = 2;
            }

            if (chooseValue[i] == 'C') {
                chooseValue[i] = 3;
            }

            if (chooseValue[i] == 'D') {
                chooseValue[i] = 4;
            }

        }
        //错题
        var err = [];
        //正确个数
        var correctCount = 0;
        //正确答案
        for (var i = 0; i < that.data.json.length; i++) {
            if (chooseValue[i] != that.data.json[i][5]) {
                err[i] = chooseValue[i];
            } else {
                correctCount++;
                err[i] = 0;
            }
        }
        that.setData({
            err: err,
        })
        //正确率
        var accuracy;
        accuracy = correctCount / that.data.json.length;
        params.accuracy = accuracy;
        params.lastqid = index;
        //使用时间
        that.checkTime();
        var hour, minu, senc;
        var time = 0;
        hour = that.data.Hour;
        minu = that.data.Minu;
        senc = that.data.Senc;
        time = senc + minu * 60 + hour * 3600;
        params.wastetime = time;
        //this.mybox.hideBox();
        var url = "/study/handinpaper";
        api.sendPosts(url, params,
            function (res) {

            })
        wx.navigateTo({
            url: '../testResult/testResult',
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('json', that.data.json)
                res.eventChannel.emit('err', that.data.err)
                res.eventChannel.emit('chooseValue', that.data.chooseValue)
                res.eventChannel.emit('colllist', that.data.colllist)
                res.eventChannel.emit('parmas', that.data.parmas)
            }
        })
    },
    //倒计时控件
    checkTime: function () {
        const that = this;
        var h, m, s;
        h = 0;
        m = 59;
        s = 59;
        var hour = that.data.Hour;
        var minu = that.data.Minu;
        var senc = that.data.Senc;
        hour = h - that.data.timer_H;
        minu = m - that.data.timer_M;
        senc = s - that.data.timer_S;
        if (senc != 59) {
            senc++;
        } else {
            senc = 0;
            minu = 1;
        }
        that.setData({
            Hour: hour,
            Minu: minu,
            Senc: senc,
        })
    },
    times: function () {
        const that = this;
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        //获取当前时间
        var n = timestamp * 1000;
        var date = new Date(n);
        //年
        var Y = date.getFullYear();
        //月
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        //日
        var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        //时
        var h = date.getHours();
        //分
        var m = date.getMinutes();
        //秒
        var s = date.getSeconds();
        var s1 = s + m * 60 + h * 3600;
        that.data.endTimes = s1;
        if (that.data.startTimes == 0) {
            that.data.startTimes = s1;
        }
        that.data.wastetime = that.data.endTimes - that.data.nowTimes; //当次时间
        that.data.totalwastetime = s1 - that.data.startTimes; //公用时间
        that.data.nowTimes = that.data.endTimes;



    },
    showMyAnswer:function(){
        
    }
})